from datetime import timedelta
import datetime
from models.model import *
from updateInfo import getCurrentUserGraph

def buildStockGraph(currentTrend, type, buyingDate, buyingPrice):
    """ Build a stock graph with Google visualization """
    ret_graph_text=""
    # Working on a single stock (not ETF)
    if type==1:
        # Build adjusted sesonality graph
        last30DaysCalc=currentTrend.last30Days
        Stocklength=len(last30DaysCalc)
        ret_graph_text+="dataGraph.addColumn('date', 'Date');\n"
        ret_graph_text+="dataGraph.addColumn('number', 'Stock Value (%s)');\n" % currentTrend.stockname.capitalize()
        ret_graph_text+="dataGraph.addColumn('string', 'title1');\n"
        ret_graph_text+="dataGraph.addColumn('string', 'text1');\n"
        ret_graph_text+="dataGraph.addRows([\n"        

        todayDate=currentTrend.updatedate
        i=0
        # Flag for checking when is the stock buying date
        peakFlag=0
        # Init max and min
        maxPeak=0
        minPeak=100
        for stockValue in last30DaysCalc:
            numday=timedelta(days=Stocklength-i-1)
            currentDay=(todayDate-numday).strftime("%Y,%m,%d")
            if peakFlag==0 and currentDay==buyingDate:
                newsHead="'Buying Date<BR />'"
                newsBody="'At $%.2f'" % buyingPrice
                originStockValue=stockValue
                minPeak, maxPeak = findMaxMinValues(last30DaysCalc, i)
                peakFlag=1
            else:
                newsHead="undefined"
                newsBody="undefined"
                if peakFlag==1:
                    if stockValue==minPeak:
                        newsHead="'Min Value<BR />'"
                        newsBody="'Investment value: $%.2f'" % (float(stockValue) / float(originStockValue) * float(buyingPrice))
                    elif stockValue==maxPeak:
                        newsHead="'Max Value<BR />'"
                        newsBody="'Investment value: $%.2f'" % (float(stockValue) / float(originStockValue) * float(buyingPrice))

            ret_graph_text+="[new Date(%s), %.2f, %s, %s]" % (currentDay, stockValue, newsHead, newsBody)
            i=i+1
            if i!=Stocklength:
                ret_graph_text+=",\n"
        ret_graph_text+="\n]);\n"
        
    # Working on ETF (not a single stock)    
    if type==2:
        ETFList=[]
        ETFlength=len(currentTrend.stocklist)
        j=0
        ret_graph_text+="dataGraph.addColumn('date', 'Date');\n"
        while j < ETFlength:
            currentStock=db.get(currentTrend.stocklist[j])
            ETFList.append(currentStock.last30Days)
            if j==0:
                minlen=len(currentStock.last30Days)
            else :
                if len(currentStock.last30Days)<minlen:
                    minlen=len(currentStock.last30Days)
            
            ret_graph_text+="dataGraph.addColumn('number', 'Stock Value (%s)');\n" % currentStock.stockname.capitalize()
            ret_graph_text+="dataGraph.addColumn('string', 'title%d');\n" % (j+1)
            ret_graph_text+="dataGraph.addColumn('string', 'text%d');\n" % (j+1) 
            j+=1
            
        #Currently taking last day
        todayDate=currentTrend.updatedate

        ret_graph_text+="dataGraph.addRows([\n"
        for i in range (0, minlen):
            numday=timedelta(days=i)
            ret_graph_text+="[new Date(%s)"  % (todayDate-numday).strftime("%Y,%m,%d")
            for stock in ETFList:
                ret_graph_text+=", %.2f, undefined, undefined" % stock[len(stock)-1-i]
            ret_graph_text+="]"
            if i!=minlen:
                ret_graph_text+=",\n"    
        ret_graph_text+="\n]);\n"                                                  
        
    return ret_graph_text
    
def findMaxMinValues(list, index):
    """ Find a min and max value ina list from a given index """    
    for i in range (index,len(list)):
        if i==index:
            min=max=list[i]
        else:
            if list[i]<min:
                min=list[i]
            elif list[i]>max:
                max=list[i]
    return min, max

def buildUserGraph(user):
    """ Build a user bank amount with Google visualization """
    userHisList=getCurrentUserGraph(user).history
    HislistLength=len(userHisList)
    todayDate=datetime.datetime.now()
    ret_graph_text="dataGraph.addRows(%d);\n" % HislistLength
    i=0

    for p in userHisList:
        numday=timedelta(days=HislistLength-i)
        ret_graph_text+="dataGraph.setValue(%d, 0, '%s');\n" % (i, (todayDate-numday).strftime("%Y-%m-%d"))
        ret_graph_text+="dataGraph.setValue(%d, 1, %f);\n" % (i, p)
        i=i+1
    return ret_graph_text

def graphHistoryDays():
    """ Number of days to show in history graph (can be global var, but future implementation demands a function) """
    return 30

def createGraphForTwoUsers(user1,user2):
    """ Build a compare graph between 2 users with Google visualization """
    user1Graph=getCurrentUserGraph(user1).history
    user2Graph=getCurrentUserGraph(user2).history
    user1GraphLen=len(user1Graph)
    user2GraphLen=len(user2Graph)
    user1Name=user1.nickname().capitalize()
    user2Name=user2.nickname().capitalize()
    # Get number of days to show
    GrapgHisLength=max(user1GraphLen,user2GraphLen)

    
    todayDate=datetime.datetime.now()
    ret_graph_text="dataGraph.addColumn('number', '%s');\ndataGraph.addColumn('number', '%s');" % (user1Name, user2Name)
    ret_graph_text+="dataGraph.addRows(%d);\n" % GrapgHisLength
    i1=0
    i2=0
    for i in range(0,GrapgHisLength):
        numday=timedelta(days=GrapgHisLength-i)
        ret_graph_text+="dataGraph.setValue(%d, 0, '%s');\n" % (i, (todayDate-numday).strftime("%Y-%m-%d"))
        if GrapgHisLength-i<=user1GraphLen:
            ret_graph_text+="dataGraph.setValue(%d, 1, %f);\n" % (i, user1Graph[i1])
            i1+=1
        else:
            ret_graph_text+="dataGraph.setValue(%d, 1, 0.0);\n" % (i)
            
        if GrapgHisLength-i<=user2GraphLen:
            ret_graph_text+="dataGraph.setValue(%d, 2, %f);\n" % (i, user2Graph[i2])
            i2+=1
        else: 
            ret_graph_text+="dataGraph.setValue(%d, 2, 0.0);\n" % (i)
    
    return ret_graph_text
